package com.webside.points.wechat;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Repository;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.webside.points.model.SendMessageEntity;

@Repository
public class Wechat {

	public static void requestCode(HttpServletResponse response,HttpServletRequest request){
		StringBuilder buffer=new StringBuilder();
		try {
			String redirect_uri = URLEncoder.encode(Constant.REALM_URL +"service/issue.jsp", "UTF-8");
			/*String redirectPage = "/service/index.jsp";
			String host = request.getRequestURL().toString();
			host = host.replaceAll(request.getServletPath(),  redirectPage);
			String redirect_uri = URLEncoder.encode(host, "UTF-8");
			System.out.println(redirect_uri);*/
			
			buffer.append(WeChatConfig.CODE_URL);
			buffer.append("?appid="+WeChatConfig.APP_ID);
			buffer.append("&redirect_uri="+redirect_uri);
			buffer.append("&response_type=code");
			buffer.append("&scope=snsapi_userinfo");
			buffer.append("&state=STATE");
			buffer.append("#wechat_redirect");
			
			response.sendRedirect(buffer.toString());
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void getOpenId(String code,HttpServletRequest request,HttpServletResponse response){
		StringBuilder buffer=new StringBuilder();
		buffer.append(WeChatConfig.OPENID_URL);
		buffer.append("?appid="+WeChatConfig.APP_ID);
		buffer.append("&secret="+WeChatConfig.APP_SECRET);
		buffer.append("&code="+code);
		buffer.append("&grant_type=authorization_code");
		
		String jsonResult = HttpUtil.sendGet(buffer.toString());
		
		ObjectMapper mapper = new ObjectMapper();

		Map<?, ?> result = null;
		try {
			result = mapper.readValue(jsonResult, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String openId =null;
		if (result != null) {
			openId = (String) result.get("openid");
			String accessToken = (String) result.get("access_token");
			
			Map<?, ?> map=getUserInfo(accessToken,openId);
			
			request.getSession().setAttribute("map", map);
			
			request.getSession().setAttribute("openId", openId);
			
			try {
				response.sendRedirect("../user/insert");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static Map<? ,?> getUserInfo(String accessToken,String openId){
		StringBuilder buffer=new StringBuilder();
		buffer.append(WeChatConfig.USER_INFO_URL);
		buffer.append("?access_token="+accessToken);
		buffer.append("&openid="+openId);
		buffer.append("&lang=zh_CN");
		
		String jsonResult = HttpUtil.sendGet(buffer.toString());
		
		ObjectMapper mapper = new ObjectMapper();

		Map<?, ?> result = null;
		try {
			result = mapper.readValue(jsonResult, Map.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	} 
	
public static String getRewardOrder(String openId,String amount,HttpServletRequest request){
		
		//System.out.println("donationType:"+donationType);
		String expertId = (String) request.getSession().getAttribute("expertId");
		
		String issueId = (String) request.getSession().getAttribute("issueId");
		
		String out_trade_no = UUID.randomUUID().toString().replaceAll("-", "");
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("appid", WeChatConfig.APP_ID);
		paraMap.put("attach", expertId+";"+issueId);
		paraMap.put("body", "打赏");
		paraMap.put("mch_id", WeChatConfig.MCH_ID);
		paraMap.put("nonce_str", RandomGenerator.getRandomStringByLength(16));
		paraMap.put("openid", openId);
		paraMap.put("out_trade_no", out_trade_no);
		paraMap.put("spbill_create_ip", getAddrIp(request));
		paraMap.put("total_fee", Util.amountTurnCent(amount));
		paraMap.put("trade_type", "JSAPI");
		paraMap.put("notify_url", Constant.REALM_URL +"service/reward-notify.jsp");
		String sign = Signature.getMD5Sign(paraMap);
		
		
		paraMap.put("sign", sign);
		
		
		//xml方式Post
		String xml = ArrayToXml(paraMap);
		System.out.println("参数："+xml);
		/*try {
			xml=new String(xml.getBytes("ISO8859-1") ,"UTF-8");
			System.out.println(xml);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}*/
		String xmlStr = HttpUtil.sendPost(WeChatConfig.UNIFIED_ORDER_URL, xml,false,10);
		System.out.println("返回结果："+xmlStr);
		//预付商品id
		String prepay_id = "";
		if (xmlStr.indexOf("SUCCESS") != -1) {
			try {
				Map<String, String> map = XMLParser.getMapFromXML(xmlStr);
				prepay_id = (String) map.get("prepay_id");
			} catch (Exception e) {
			}
		}
		
		System.out.println("prepay_id："+prepay_id);
		//返回数据构造
		Map<String, String> payMap = new HashMap<String, String>();
		payMap.put("appId", WeChatConfig.APP_ID);
		payMap.put("timeStamp", create_timestamp());
		payMap.put("nonceStr", RandomGenerator.getRandomStringByLength(16));
		payMap.put("package", "prepay_id=" + prepay_id);
		payMap.put("signType", "MD5");
		payMap.put("paySign", Signature.getMD5Sign(payMap));
		
		//返回JSON数据
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			return  objectMapper.writeValueAsString(payMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

	public static String getRStudyOrder(String openId,String amount,int userId,int postTypeId,HttpServletRequest request){
		
		//System.out.println("donationType:"+donationType);
		
		String out_trade_no = UUID.randomUUID().toString().replaceAll("-", "");
		Map<String, String> paraMap = new HashMap<String, String>();
		paraMap.put("appid", WeChatConfig.APP_ID);
		paraMap.put("attach", userId+";"+postTypeId);
		paraMap.put("body", "学习");
		paraMap.put("mch_id", WeChatConfig.MCH_ID);
		paraMap.put("nonce_str", RandomGenerator.getRandomStringByLength(16));
		paraMap.put("openid", openId);
		paraMap.put("out_trade_no", out_trade_no);
		paraMap.put("spbill_create_ip", getAddrIp(request));
		paraMap.put("total_fee", Util.amountTurnCent(amount));
		paraMap.put("trade_type", "JSAPI");
		paraMap.put("notify_url", Constant.REALM_URL +"service/study-notify.jsp");
		String sign = Signature.getMD5Sign(paraMap);
		
		
		paraMap.put("sign", sign);
		
		
		//xml方式Post
		String xml = ArrayToXml(paraMap);
		System.out.println("参数："+xml);
		/*try {
			xml=new String(xml.getBytes("ISO8859-1") ,"UTF-8");
			System.out.println(xml);
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}*/
		String xmlStr = HttpUtil.sendPost(WeChatConfig.UNIFIED_ORDER_URL, xml,false,10);
		System.out.println("返回结果："+xmlStr);
		//预付商品id
		String prepay_id = "";
		if (xmlStr.indexOf("SUCCESS") != -1) {
			try {
				Map<String, String> map = XMLParser.getMapFromXML(xmlStr);
				prepay_id = (String) map.get("prepay_id");
			} catch (Exception e) {
			}
		}
		
		System.out.println("prepay_id："+prepay_id);
		//返回数据构造
		Map<String, String> payMap = new HashMap<String, String>();
		payMap.put("appId", WeChatConfig.APP_ID);
		payMap.put("timeStamp", create_timestamp());
		payMap.put("nonceStr", RandomGenerator.getRandomStringByLength(16));
		payMap.put("package", "prepay_id=" + prepay_id);
		payMap.put("signType", "MD5");
		payMap.put("paySign", Signature.getMD5Sign(payMap));
		
		//返回JSON数据
		ObjectMapper objectMapper = new ObjectMapper();
		try {
			return  objectMapper.writeValueAsString(payMap);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		
		
		return null;
	}

	public static void transfersPay(String openId,String amount,HttpServletRequest request){
		String partner_trade_no = UUID.randomUUID().toString().replaceAll("-", "");
		Map<String, String> paraMap = new HashMap<String, String>();
		 paraMap.put("mch_appid", WeChatConfig.APP_ID); //公众账号appid
		 paraMap.put("mchid", WeChatConfig.MCH_ID); //商户号
		 paraMap.put("nonce_str", RandomGenerator.getRandomStringByLength(16)); //随机字符串
		 paraMap.put("partner_trade_no", partner_trade_no); //商户订单号
		 paraMap.put("openid", openId); //用户openid  
		 paraMap.put("check_name", "NO_CHECK"); //校验用户姓名选项 OPTION_CHECK
         //parm.put("re_user_name", "安迪"); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
		 paraMap.put("amount", amount); //转账金额
		 paraMap.put("desc", "test"); //企业付款描述信息
		 paraMap.put("spbill_create_ip", getAddrIp(request)); //服务器Ip地址
		 String sign = Signature.getMD5Sign(paraMap);
		 paraMap.put("sign", sign);
		 
		 String xml = ArrayToXml(paraMap);
		 System.out.println("参数："+xml);
		 
		 String xmlStr = HttpUtil.sendPost(WeChatConfig.TRANSFERS_PAY_URL, xml,true,10);
		 System.out.println("返回结果："+xmlStr);
	}

	public static String getAddrIp(HttpServletRequest request) {  
		if (request.getHeader("x-forwarded-for") == null) {  
			return request.getRemoteAddr();  
		}  
		//防止获取到两个ip
		  return request.getHeader("x-forwarded-for").split(", ")[0];  
	}  
	/**
	 * map转成xml
	 * 
	 * @param arr
	 * @return
	 */
	public static String ArrayToXml(Map<String, String> arr) {
		String xml = "<xml>";
		Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
		while (iter.hasNext()) {
			Entry<String, String> entry = iter.next();
			String key = entry.getKey();
			String val = entry.getValue();
			xml += "<" + key + ">" + val + "</" + key + ">";
		}
		xml += "</xml>";
		return xml;
	}
	
	public static String create_timestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
	
	public static String accessToken(){
		StringBuffer accessTokenUrl = new StringBuffer();
		accessTokenUrl.append(WeChatConfig.ACCESS_TOKEN_URL);
		accessTokenUrl.append("&appid=" + WeChatConfig.APP_ID);
		accessTokenUrl.append("&secret=" + WeChatConfig.APP_SECRET);
		String accessTokenJson = HttpUtil.sendGet(accessTokenUrl.toString());
		return accessTokenJson;
	}
	
	public static void sendMessage(Map<String, Map<String, String>> data,String templateId,String touser,String url){
		
		Map<?, ?> result=null;
		ObjectMapper mapper = new ObjectMapper();
		try {
			result =mapper.readValue(accessToken(), Map.class);
			System.out.println(result.get("access_token"));
		}  catch (Exception e) {
			e.printStackTrace();
		}
		String path=WeChatConfig.SEND_MESSAGE_URL+"?access_token="+result.get("access_token");
		
		SendMessageEntity sendMessageEntity=new SendMessageEntity();
		sendMessageEntity.setUrl(url);
		sendMessageEntity.setTouser(touser);
		sendMessageEntity.setTemplate_id(templateId);
		sendMessageEntity.setData(data);
		String json = JSON.toJSONString(sendMessageEntity);
		//System.out.println(json);
		  
		String xmlStr = HttpUtil.sendPost(path, json,false,10);
		System.out.println(xmlStr);
	}
	
	
	public static String mediaGet(String mediaId,String savePath){
		String filePath = null;  
		Map<?, ?> result=null;
		ObjectMapper mapper = new ObjectMapper();
		try {
			result =mapper.readValue(accessToken(), Map.class);
			//System.out.println(result.get("access_token"));
		
		String requestUrl = WeChatConfig.MEDIA_GET_URL+"?access_token="+result.get("access_token")+"&media_id="+mediaId;
		
		 URL url = new URL(requestUrl);  
		 //打开请求
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
         conn.setDoInput(true);  
         conn.setRequestMethod("GET");  
         
         //判断保存路径是否有/
         if (!savePath.endsWith("/")) {  
             savePath += "/";  
         }  
         String fileType = conn.getHeaderField("Content-Type");
         
         if(fileType.contains("image")){
        	 filePath = savePath + mediaId +".jpg";  
         }else if(fileType.contains("audio")){
        	 filePath = savePath + mediaId +".amr";  
         }

         BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());  
         FileOutputStream fos = new FileOutputStream(new File(filePath));  
         byte[] buf = new byte[8096];  
         int size = 0;  
         while ((size = bis.read(buf)) != -1)  
             fos.write(buf, 0, size);  
         fos.close();  
         bis.close();  

         conn.disconnect();  
         return filePath;
         
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		
		String templateId = "cEoV85gN0ywx9h2da_tNFS08PFHMV-iGQwz9CFxejQA";
		
		String touser = "oqxTFs9Z7Ef2HjwCeBnKGFHakGjs";
		
		String url = "www.saibaibu.com";
		
		Map<String, Map<String, String>> data = new HashMap<String,Map<String, String>>();
		
		Map<String, String> first=new HashMap<String, String>();
		first.put("value", "申请专家审核通知");
		first.put("color", WeChatConfig.MESSAGE_COLOR);
		
		Map<String, String> keyword1=new HashMap<String, String>();
		keyword1.put("value", "吴俊");
		keyword1.put("color", WeChatConfig.MESSAGE_COLOR);

		Map<String, String> keyword2=new HashMap<String, String>();
		keyword2.put("value", "我要成为发教专家！");
		keyword2.put("color", WeChatConfig.MESSAGE_COLOR);
		
		Map<String, String> remark=new HashMap<String, String>();
		remark.put("value", "点击进入，进行审核");
		remark.put("color", WeChatConfig.MESSAGE_COLOR);
		
		data.put("first",first);
		data.put("keyword1",keyword1);
		data.put("keyword2",keyword2);
		data.put("remark",remark);
		
		sendMessage(data,templateId,touser,url);
		
		/*String mediaId = "Z1sp_hkm6UnndaCoI5SxOOp5UDqqZThiq7b_aVOQJt4Tu_73nTypTKYNv2LErJ7V";
		
		String savePath = "E:/";
		
		mediaGet(mediaId,savePath);*/
		
		
		
	}
	
	
	
	
}
